package com.cxyd.modules.wms.controller;

import com.cxyd.common.page.PageData;
import com.cxyd.common.utils.Result;
import com.cxyd.common.annotation.LogOperation;
import com.cxyd.common.validator.AssertUtils;
import com.cxyd.common.validator.ValidatorUtils;
import com.cxyd.common.validator.group.AddGroup;
import com.cxyd.common.validator.group.DefaultGroup;
import com.cxyd.common.validator.group.UpdateGroup;
import com.cxyd.modules.wms.dto.OrderDTO;
import com.cxyd.modules.wms.service.OrderService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;


/**
 * 出库主单
 *
 * @author g_Cycle gengruyi01@163.com
 * @since 1.0.0 2023-04-27
 */
@RestController
@RequestMapping("wms/order")
public class OrderController {
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("page")
    @RequiresPermissions("wms:order:page")
    public Result<PageData<OrderDTO>> page(@RequestParam Map<String, Object> params){
        PageData<OrderDTO> page = orderService.page(params);

        return new Result<PageData<OrderDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @RequiresPermissions("wms:order:info")
    public Result<OrderDTO> get(@PathVariable("id") Long id){
        OrderDTO data = orderService.get(id);

        return new Result<OrderDTO>().ok(data);
    }

    @PostMapping
    @LogOperation("保存")
    @RequiresPermissions("wms:order:save")
    public Result save(@RequestBody OrderDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        orderService.save(dto);

        return new Result();
    }

    @PutMapping
    @LogOperation("修改")
    @RequiresPermissions("wms:order:update")
    public Result update(@RequestBody OrderDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        orderService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @LogOperation("删除")
    @RequiresPermissions("wms:order:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        orderService.delete(ids);

        return new Result();
    }

    @PostMapping("/upload")
    @LogOperation("单据导入")
    @RequiresPermissions("wms:order:upload")
    public Result upload(MultipartFile file) {
        try {
            orderService.uploadFile(file);
        } catch (Exception e) {
            return new Result().error("上传失败，请重试!" + e.getMessage());
        }
        return new Result().ok("上传成功！");
    }
}